let mongoose = require('mongoose')
mongoose.connect("mongodb://127.0.0.1:27017/blog")
let db = mongoose.connection

db.on('error', console.error.bind(console, 'connect error:'))
db.once('open', () => {
  console.log('connected!!!')
})

//集合关联 populate

//User
let userSchema = new mongoose.Schema({
  username: {
    type: String
  },
  password: {
    type: String,
    select: false
  },
  articles: [
    {
      type: mongoose.SchemaTypes.ObjectId,
      //ref 关联 集合model的名字
      ref: "Article"
    }
  ]
})

//Article
let articleSchema = new mongoose.Schema({
  title: {
    type: String,
    unique: true,  //是否为必填项,
    default: "默认文章标题" + Date.now,
  },
  body: {
    type: String
  },
  author: {
    type: mongoose.SchemaTypes.ObjectId,
    ref: 'User'
  }
})


/*
  登录一个用户 

  获取用户文章列表() => 文章document必须有字段存储用户id

  获取文章 => 标题 内容 发表时间 点赞数量 查看数量 评论数量 uid(用户名 用户签名 用户头像...) (评论列表)

  关联查询

  
  populate(关联字段,"select字段1 select字段2")

*/




let User = mongoose.model('User', userSchema)
let Article = mongoose.model('Article', articleSchema)


// Article.findOne({ 'title': '测试文章1' }).populate('author', "username").then(doc => {
//   console.log(doc)
//   // let authorId = doc.author

// }).catch(err => {
//   console.log(err.errors)
// })

User.findOne({ "username": "zhagnsan" }).populate('articles', "title").then(doc => {
  console.log(doc)
}).catch(err => {
  console.log(err)
})

/*
  生成
  let id =  mongoose.SechemaTypes.ObjectId() => 生成一个 ObjectId
  转换
  String => ObjectId
    mongoose.Types.ObjectId(StringId)
  ObjectId => String
    id.toString()

*/
let uid = mongoose.Types.ObjectId("5fd75ef536de7e4288e88b9f")
// console.log(uid instanceof mongoose.Types.ObjectId)

// Article.create({ title: "测试文章1", body: "哈哈哈哈哈哈", author: uid }).then(doc => {
//   console.log(doc)
//   let aid = doc._id;
//   User.findByIdAndUpdate(uid, { $push: { articles: aid } }).then(doc => {
//     console.log(doc)
//   }).catch(err => {
//     console.log(err)
//   })
// }).catch(err => {
//   console.log(err.errors)
// })

// User.create({ username: "zhagnsan", password: "123&32d1!", articles: [] }).then(doc => {
//   console.log(doc)
// }).catch(err => {
//   console.log(err.errors)
// })

